import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: []
  },
  mutations: {
    setList (state, val) {
      state.list = val
    },
    // 输入框
    inpt (state, obj) {
      state.list.forEach(item => {
        if (item.id == obj.id) {
          item.goods_count = obj.value
        }
      })
    },
    // 全选
    inversion (state, val) {
      // console.log(val);
      state.list.forEach(item => item.goods_state = val)
    },
    // 加减
    add (state, id) {
      state.list.forEach(item => {
        if (item.id == id) {
          item.goods_count++
        }
      })
    },
    upp (state, id) {
      state.list.forEach(item => {
        if (item.id == id && item.goods_count > 1) {
          item.goods_count--
        }
      })
    },
  },
  actions: {
    async getList (store) {
      const res = await axios({
        url: '/api/cart'
      })
      store.commit('setList', res.data.list)
    }
  },
  getters: {
    // 总数
    allNumber (state) {
      return state.list.reduce((sum, item) => {
        if (item.goods_state) {
          sum += item.goods_count
        }
        return sum
      }, 0)
    },
    //总价
    totalCost (state) {
      return state.list.reduce((sum, item) => {
        if (item.goods_state) {
          sum += item.goods_count * item.goods_price
        }
        return sum
      }, 0)
    },
    // 小选影响全选
    selectAll (state) {
      return state.list.every(item => item.goods_state)
    }
  },
  modules: {
  }
})
